package com.sbox.album.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.sbox.util.AlbumConst;
import com.sbox.util.AlbumLog;

import android.graphics.Bitmap;

public class CacheManager {
	
	private List<Integer> mCacheIndex = new ArrayList<Integer>(100);
	private HashMap<Integer, Bitmap> mBitmapCache = new HashMap<Integer, Bitmap>(100);	
	
	
	private static CacheManager sCacheManager = null;
	public static CacheManager getInstance() {
		if( sCacheManager == null )
			sCacheManager = new CacheManager();
		
		return sCacheManager;
	}
	
	private CacheManager() {
		
	}
	
	public void clearCache() {
		mCacheIndex.clear();
		mBitmapCache.clear();
		System.gc();
	}
	
	public void cacheImage(int index, Bitmap bmp) {			
		int size = 0;
		
		synchronized(mBitmapCache) {
			//AlbumLog.info("cacheImage: " + mBitmapCache.size());			
			mBitmapCache.put(index, bmp);
			mCacheIndex.add(index);
			
			size = mCacheIndex.size();
			if( size >= AlbumConst.ALBUM_CACHE_MAX_SIZE )
			{					
				AlbumLog.info("clearCache: " + size);
				
				size = size/2;
				for( int i=0; i<size; i++ ) {
					mBitmapCache.remove(mCacheIndex.remove(i));
				}
				System.gc();
				AlbumLog.info("clearCache done, size= " + size);
			}
		}
		
	}
	
	public Bitmap findImage(int index) {
		synchronized(mBitmapCache) {
			return mBitmapCache.get(index);
		}
	}
}
